<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
 *
 * @package		anime
 * @author		Tran Hoang Thien (thienhb12@gmail.com)
 * @copyright   PHP TEAM
 * @link		http://phpandmysql.net
 * @since		Version 1.0
 * @phone       0944418192
 *
 */
	class Film extends My_Controller{
		
		public function __construct(){
			parent:: __construct();
			$this->load->model('film_model');
			$this->load->model('category_model');
			$this->load->model('mcountry');
			$this->load->model('film_info_model');
			$this->load->model('episode_model');
			$this->load->model('episode_error');
			$this->load->model('film_error');
			$this->load->library('form_validation');
			$this->load->helper('url');
			if(!$this->session->userdata("session_user") || $this->session->userdata("session_level") != 1){
				redirect(base_url()."admin/login");
			}
		}

		public function index(){
			$data['title']             = 'List film';
			$data['color']             = '#33925c';
			$data['template']          = 'film/list_film';
			$config['base_url']        = base_url('admin/film/index');
			$config['total_rows']      = $this->film_model->count_all();
			$config['per_page']        = 20;
			$config['uri_segment']     = '4';
			$config['first_link']      = '<<';
			$config['last_link']       = '>>';
			$config['first_tag_open']  = '<li class="click">';
			$config['first_tag_close'] = '</li>';
			$config['last_tag_open']   = '<li class="click">';
			$config['last_tag_close']  = '</li>';
			$config['prev_tag_open']   = '<li class="click">';
			$config['prev_tag_close']  = '</li>';
			$config['next_tag_open']   = '<li class="click">';
			$config['next_tag_close']  = '</li>';
			$config['num_tag_open']    = '<li class="click">';
			$config['num_tag_close']   = '</li>';
			$config['next_link']       = 'Next';
			$config['prev_link']       = 'Prev';
			$config['cur_tag_open']    = '<li class="active"><a>';
			$config['cur_tag_close']   = '</a></li>';
			$this->load->library("pagination");
			$this->pagination->initialize($config);
			$start                     = $this->uri->segment(4)?$this->uri->segment(4):0;
			$param                     = array();
			$cate_param                = array();
			$country_param             = array();
			$cate_param['select']      = array('idcate','namecate');	
			$country_param['select']   = array('idcountry','namecountry');	
			$param['select']           = array('name','name_en','thumb','film_year','category','status','country','option_film','idphim','slider_status');
			$param['limit']            = array($config['per_page'] ,$start);
			$param['order']			   = array('timepost','DESC');	
			$data['result']            = $this->film_model->get_list($param);
			$data['cate_result']       = $this->category_model->get_list($cate_param);
			$data['county_result']     = $this->mcountry->get_list($country_param);
			$info_country              = array();
			$info_cate                 = array();
			
			if($data['county_result'] != NULL){	
				foreach ($data['county_result'] as $value) {
					$info_country[$value['idcountry']] = $value['namecountry'];
				}
			}
			
			if($data['cate_result'] != NULL){	
				foreach ($data['cate_result'] as $value) {
					$info_cate[$value['idcate']] = $value['namecate'];
				}
			}
			$data['info_country']      = $info_country;
			$data['info_cate']         = $info_cate;

			$this->load->view("layout",$data);
		}

		public function list_all(){
			$data['title']             = 'List film';
			$data['color']             = '#33925c';
			$data['template']          = 'film/list_film';
			$config['base_url']        = base_url('admin/film/index');
			$config['total_rows']      = $this->film_model->count_all();
			$config['per_page']        = 20;
			$config['uri_segment']     = '4';
			$config['first_link']      = '<<';
			$config['last_link']       = '>>';
			$config['first_tag_open']  = '<li class="click">';
			$config['first_tag_close'] = '</li>';
			$config['last_tag_open']   = '<li class="click">';
			$config['last_tag_close']  = '</li>';
			$config['prev_tag_open']   = '<li class="click">';
			$config['prev_tag_close']  = '</li>';
			$config['next_tag_open']   = '<li class="click">';
			$config['next_tag_close']  = '</li>';
			$config['num_tag_open']    = '<li class="click">';
			$config['num_tag_close']   = '</li>';
			$config['next_link']       = 'Next';
			$config['prev_link']       = 'Prev';
			$config['cur_tag_open']    = '<li class="active"><a>';
			$config['cur_tag_close']   = '</a></li>';
			$this->load->library("pagination");
			$this->pagination->initialize($config);
			$start                     = $this->uri->segment(4)?$this->uri->segment(4):0;
			$param                     = array();
			$cate_param                = array();
			$country_param             = array();
			$cate_param['select']      = array('idcate','namecate');	
			$country_param['select']   = array('idcountry','namecountry');	
			$param['select']           = array('name','name_en','thumb','film_year','category','status','country','option_film','idphim','slider_status');
			$param['limit']            = array($config['per_page'] ,$start);
			$param['order']			   = array('timepost','DESC');	
			$data['result']            = $this->film_model->get_list($param);
			$data['cate_result']       = $this->category_model->get_list($cate_param);
			$data['county_result']     = $this->mcountry->get_list($country_param);
			$info_country              = array();
			$info_cate                 = array();
			
			if($data['county_result'] != NULL){	
				foreach ($data['county_result'] as $value) {
					$info_country[$value['idcountry']] = $value['namecountry'];
				}
			}
			
			if($data['cate_result'] != NULL){	
				foreach ($data['cate_result'] as $value) {
					$info_cate[$value['idcate']] = $value['namecate'];
				}
			}
			$data['info_country']      = $info_country;
			$data['info_cate']         = $info_cate;

			$this->load->view($data['template'],$data);
		}

		public function add(){
			$data['title']          = 'Add film';
			$data['color']          = '#33925c';
			$data['template']       = 'film/add_film';
			$cate                   = array();
			$cate['select']         = array('idcate','namecate');
			$cate['where']          = array('status' => 1);
			$data['result_cate']    = $this->category_model->get_list($cate);
			$country                = array();
			$country['select']      = array('idcountry','namecountry');
			$country['where']       = array('status' => 1);
			$data['result_country'] = $this->mcountry->get_list($country);
			$check_request          = $this->input->post();
			if($check_request != NULL){
				$this->form_validation->set_rules('name','name', 'required|trim|xss_clean');
				$this->form_validation->set_rules('name_en','name english','trim|xss_clean');
				$this->form_validation->set_rules('meta', 'meta','required|trim|xss_clean');
				$this->form_validation->set_rules('description', 'description','required|trim|xss_clean');
				$this->form_validation->set_rules('film_year', 'film year','trim|xss_clean|numeric');
				$this->form_validation->set_rules('duration', 'duration','trim|xss_clean');
				$this->form_validation->set_rules('thumb', 'thumb','required|trim|xss_clean|prep_url');
				$this->form_validation->set_rules('big_thumb', 'big thumb','required|trim|xss_clean|prep_url');
				$this->form_validation->set_rules('quaylity', 'quaylity','trim|xss_clean');
				$this->form_validation->set_rules('trailer', 'trailer','trim|xss_clean');
				$this->form_validation->set_rules('content', 'content','required|trim');
				$this->form_validation->set_rules('search', 'search','trim|xss_clean');
				if($this->form_validation->run() == FALSE){
					$data['title']          = 'Thêm mới thể loại';
					$data['color']          = '#33925c';
					$data['template']       = 'film/add_film';
					$cate                   = array();
					$cate['select']         = array('idcate','namecate');
					$cate['where']          = array('status' => 1);
					$data['result_cate']    = $this->category_model->get_list($cate);
					$country                = array();
					$country['select']      = array('idcountry','namecountry');
					$country['where']       = array('status' => 1);
					$data['result_country'] = $this->mcountry->get_list($country);
					$this->load->view('layout',$data);
				}else{
					$name         = RemoveHack($this->input->post('name'));
					$name_en      = RemoveHack($this->input->post('name_en'));
					
					if($this->input->post('category') != NULL ){
						$category     = $this->input->post('category');
						$str_category = implode(',', $category);
					}else{
						$str_category = '';
					};
					
					if($this->input->post('tags') != NULL){
						$tags     = $this->input->post('tags');
						$arr_tags = explode(',', $tags);
					}else{
						$tags     = '';
						$arr_tags = '';
					};
					
					$option_film  = $this->input->post('option_film');
					$hot          = $this->input->post('hot');
					$decu         = $this->input->post('decu');
					$meta         = RemoveHtml(fillter($this->input->post('meta')));
					$description  = RemoveHtml(fillter($this->input->post('description')));
					$film_year    = fillter($this->input->post('film_year'));
					$duration     = fillter($this->input->post('duration'));
					$thumb        = fillter($this->input->post('thumb'));
					$big_thumb    = fillter($this->input->post('quaylity'));
					$trailer      = fillter($this->input->post('trailer'));
					$director     = fillter($this->input->post('director'));
					$actor        = fillter($this->input->post('actor'));
					$content      = RemoveHtml($this->input->post('content'));
					$country      = $this->input->post('country');
					if($this->input->post('search') != NULL){
						$arr_search   =	explode(',', $this->input->post('search'));
						$str_search   = array();
						foreach ($arr_search as $value) {
							$str_search[] = str_replace(' ', '-',strtolower(str_replace('%','n',replace($value))));
						}
						$search       = implode(',', $str_search);
					}else{
						$search       = str_replace(' ', '-',strtolower(str_replace('%','n',replace($name))));
					}
					$post_author  = $this->session->userdata('session_user_id');
					$rewrite      = str_replace(' ', '-',strtolower(str_replace('%','n',replace($name))));
					if($this->input->post('status') != NULL){
						$status  = $this->input->post('status');
					}else{
						$status = 2;
					}
					
					$db = array(
						'name'        => $name,
						'name_en'     => $name_en,
						'rewrite'     => $rewrite,
						'big_thumb'   => $big_thumb,
						'thumb'       => $thumb,
						'post_author' => $post_author,
						'trailer'     => $trailer,
						'status'      => $status,
						'film_year'   => $film_year,
						'actor'       => $actor,
						'director'    => $director,
						'country'     => $country,
						'category'    => $str_category,
						'content'     => UnHtmlChars($content),
						'keywords'    => $meta,
						'description' => $description,
						'search'      => $search,
						'decu'        => $decu,
						'hot'         => $hot,
						'option_film' => $option_film,
						'duration'    => $duration,
						'timepost'	  => time()
					);
					$new_id      = $this->film_model->save($id = false,$db);
					$tag_data    = array(
						'idphim' => $new_id,
						'tag'    => $tags,
					);
					$tag_rewite       = array();
					if($arr_tags != NULL){
						foreach($arr_tags as $value){
							$tag_rewite[] = str_replace(' ', '-',strtolower(str_replace('%','n',replace($value)))); 
						}
					}
					$tag_data['tags_rewrite'] =  implode(',',$tag_rewite);
					$this->film_info_model->save($id = false,$tag_data);
					redirect(base_url("admin/film"));
				}
			}else{
				$this->load->view('layout',$data);
			}
		}

		public function edit(){
			$data['title']          = "Edit film info";
			$data['color']          = "#33925c";
			$data['template']       = 'film/edit_film';
			$var                    = array();
			$id                     = $this->uri->segment(4);
			$cate                   = array();
			$cate['select']         = array('idcate','namecate');
			$cate['where']          = array('status' => 1);
			$data['result_cate']    = $this->category_model->get_list($cate);
			$country                = array();
			$country['select']      = array('idcountry','namecountry');
			$country['where']       = array('status' => 1);
			$data['result_country'] = $this->mcountry->get_list($country);
			if(isset($id)){
				if($this->input->post() != NULL){
					$id = $this->uri->segment(4);
					$this->form_validation->set_rules('name','name', 'required|trim|xss_clean');
					$this->form_validation->set_rules('name_en','name english','trim|xss_clean');
					$this->form_validation->set_rules('meta', 'meta','required|trim|xss_clean');
					$this->form_validation->set_rules('description', 'description','required|trim|xss_clean');
					$this->form_validation->set_rules('film_year', 'film year','trim|xss_clean|numeric');
					$this->form_validation->set_rules('duration', 'duration','trim|xss_clean');
					$this->form_validation->set_rules('thumb', 'thumb','required|trim|xss_clean|prep_url');
					$this->form_validation->set_rules('big_thumb', 'big thumb','required|trim|xss_clean|prep_url');
					$this->form_validation->set_rules('quaylity', 'quaylity','trim|xss_clean');
					$this->form_validation->set_rules('trailer', 'trailer','trim|xss_clean');
					$this->form_validation->set_rules('content', 'content','required|trim');
					$this->form_validation->set_rules('search', 'search','trim|xss_clean');
					if($this->form_validation->run() == FALSE){
						$data['title']         = 'Sửa thông tin';
						$data['color']         = '#33925c';
						$data['template']      = 'film/edit_film';
						$param                 = array('name','name_en','big_thumb','thumb','idphim','trailer','director','film_year','content','search','quaylity','keywords','description','actor','option_film','country','category','duration','decu','hot');
						$tags_param            = array('idphim','tag');
						$select_param          = array('decu','hot');
						$data['result']        = $this->film_model->get_info($id,$param);
						$data['tags_result']   = $this->film_info_model->get_info($id,$tags_param);
						$arr_cate              = array();
						if($data['result']['category'] != NULL){
							$str_cate              = explode(',',$data['result']['category']);
							foreach ($str_cate as $value) {
								$arr_cate[$value]  = 'checked';
							}
						}
						$data['check_cate']		   = $arr_cate;
						$data['search']            = str_replace('-',' ', $data['result']['search']);
						$this->load->view('layout',$data);
					}else{

						$name         = RemoveHack($this->input->post('name'));
						$name_en      = RemoveHack($this->input->post('name_en'));
						if($this->input->post('category') != NULL){
							$category     = $this->input->post('category');
							$str_category = implode(',', $category);
						}else{
							$str_category = '';
						};
						if($this->input->post('tags') != NULL){
							$tags         = $this->input->post('tags');
							$arr_tags     = explode(',', $tags);
						}else{
							$tags         = '';
							$arr_tags     = '';
						};
						$option_film      = $this->input->post('option_film');
						$hot              = $this->input->post('hot');
						$decu             = $this->input->post('decu');
						$meta             = RemoveHack(fillter($this->input->post('meta')));
						$description      = RemoveHack(fillter($this->input->post('description')));
						$film_year        = fillter($this->input->post('film_year'));
						$duration         = fillter($this->input->post('duration'));
						$thumb            = fillter($this->input->post('thumb'));
						$big_thumb        = fillter($this->input->post('big_thumb'));
						$quaylity         = fillter($this->input->post('quaylity'));
						$trailer          = fillter($this->input->post('trailer'));
						$director         = fillter($this->input->post('director'));
						$actor            = fillter($this->input->post('actor'));
						$content          = RemoveHtml($this->input->post('content'));
						$country          = $this->input->post('country');
						if($this->input->post('search') != NULL){
							$arr_search   =	explode(',', $this->input->post('search'));
							$str_search   = array();
							foreach ($arr_search as $value) {
								$str_search[] = str_replace(' ', '-',strtolower(str_replace('%','n',replace($value))));
							}
							$search       = implode(',', $str_search);
						}else{
							$search       = str_replace(' ', '-',strtolower(str_replace('%','n',replace($name))));
						}
						
						$post_author      = $this->session->userdata('session_user_id');
						$rewrite          = str_replace(' ', '-',strtolower(str_replace('%','n',replace($name))));
						if($this->input->post('status') != NULL){
							$status  = $this->input->post('status');
						}else{
							$status = 2;
						}
						
						$db = array(
							'name'        => $name,
							'name_en'     => $name_en,
							'rewrite'     => $rewrite,
							'big_thumb'   => $big_thumb,
							'thumb'       => $thumb,
							'post_author' => $post_author,
							'trailer'     => $trailer,
							'status'      => $status,
							'film_year'   => $film_year,
							'actor'       => $actor,
							'director'    => $director,
							'country'     => $country,
							'category'    => $str_category,
							'content'     => $content,
							'keywords'    => $meta,
							'description' => $description,
							'search'      => $search,
							'option_film' => $option_film,
							'quaylity'    => $quaylity,
							'duration'    => $duration,
							'decu'        => $decu,
							'hot'         => $hot,
							'timepost'	  => time()
						);
						
						$this->film_model->save($id,$db);
						$tag_data    = array(
							'idphim' => $id,
							'tag'    => $tags,
						);
						$tag_rewite           = array();
						if($arr_tags != NULL){
							foreach($arr_tags as $value){
								$tag_rewite[] = str_replace(' ', '-',strtolower(str_replace('%','n',replace($value)))); 
							}
						}
						$tag_data['tags_rewrite'] =  implode(',',$tag_rewite);
						$this->film_info_model->delete($id);
						$this->film_info_model->save($id = false,$tag_data);
						redirect(base_url("admin/film"));
					}
				}else{
					if($id != NULL){
						$param                     = array('name','name_en','big_thumb','thumb','idphim','trailer','director','film_year','content','search','quaylity','keywords','description','actor','option_film','country','category','duration','hot','decu');
						$tags_param                = array('idphim','tag');
						$select_param              = array('decu','hot');
						$data['result']            = $this->film_model->get_info($id,$param);
						$data['tags_result']       = $this->film_info_model->get_info($id,$tags_param);
						$arr_cate                  = array();
						if($data['result']['category'] != NULL){
							$str_cate              = explode(',',$data['result']['category']);
							foreach ($str_cate as $value) {
								$arr_cate[$value]  = 'checked';
							}
						}
						$data['check_cate']		   = $arr_cate;
						$data['search']            = str_replace('-',' ', $data['result']['search']);
						$this->load->view('layout',$data);
					}
				}
			}else{
				redirect(base_url("admin/film"));
			}
		}

		public function delete(){
			$id = $this->uri->segment(4);
			if($id != NULL){	
				$this->film_model->delete($id);
				$this->film_info_model->delete($id);
				$param           = array();
				$param['select'] = array('sub');
				$param['where']  = array('idphim'=>$id);
				$result          = $this->episode_model->get_list($param);
				if($result != NULL){
					foreach ($result as $value) {
						@unlink($value['sub']);
					}
				}
				$this->episode_model->delete_rule(array('idphim' => $id));
				redirect(base_url("admin/film"));
			}
		}

		public function change_status(){
			if($this->input->post('action') != NULL){
				$data = array();
				$id   = (int)$this->input->post('id');
				if($this->input->post('status') == 'publish'){
					$data['status'] = 1;
					$this->film_model->save($id,$data);
				}elseif($this->input->post('status') == 'unpublish'){
					$data['status'] = 2;
					$this->film_model->save($id,$data);
				}
			}
		}

		public function change_slider(){
			if($this->input->post('action') != NULL){
				$data = array();
				$id   = (int)$this->input->post('sid');
				if($this->input->post('status') == 'publish'){
					$data['slider_status'] = 1;
					$this->film_model->save($id,$data);
				}elseif($this->input->post('status') == 'unpublish'){
					$data['slider_status'] = 2;
					$this->film_model->save($id,$data);
				}
			}
		}

		public function bulk_action(){
			$var      = array();
			$request  = $this->input->post();
			if(!empty($request)){
				$type = $this->uri->segment(4);
				$uid  = $this->input->post('id');
				if($type == 'delete'){
					if(!empty($uid)){
						foreach($uid as $value){
							$data = array('idphim' => $value);
							$param           = array();
							$param['select'] = array('sub');
							$param['where']  = array('idphim'=>$value);
							$result          = $this->episode_model->get_list($param);
							if($result != NULL){
								foreach ($result as $val) {
									@unlink($val['sub']);
								}
							}
							$this->film_model->delete_rule($data);
							$this->episode_error->delete_rule($data);
							$this->film_error->delete_rule($data);
							$this->episode_model->delete_rule($data);
						}
					}
					$var['action'] = 'delete';
				}elseif($type == 'publish'){
					if(!empty($uid)){
						foreach($uid as $value){
							$where = array('idphim'=> $value);
							$data  = array('status' => 1) ;
							$this->film_model->update_rule($where,$data);
						}
					}
					$var['action'] = 'publish';
				}elseif($type == 'unpublish'){
					if(!empty($uid)){
						foreach($uid as $value){
							$where = array('idphim'=> $value);
							$data  = array('status' => 2) ;
							$this->film_model->update_rule($where,$data);
						}
					}
					$var['action'] = 'unpublish';
				}
				$var['error'] = 0;
			}else{
				$var['error'] = 1;
			}
			$var['url'] = base_url('admin/film/list_all');
			exit(json_encode($var));
		}
	}